<?php

namespace App\Services\Notes;

use App\Models\NoteClassifyModel;
use App\Models\UserNotesModel;
use App\Services\BaseServices;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class NotesServices extends BaseServices
{

    /**
     * 返回分类.
     *
     * @return array[]
     */
    public function notesClassify(): array
    {
        return NoteClassifyModel::getInstance()->where(['status' => 1])->orderBy('id', 'asc')->get()->toArray();
    }

    /**
     * 添加笔记.
     *
     * @param Request $request
     * @return bool
     */
    public function addNotes(Request $request): bool
    {
        $uId = $request->user()->id;
        $classify = $request->input('classify');
        $content = $request->input('content');

        $model = UserNotesModel::getInstance();

        DB::beginTransaction();
        try {
            $model->title = $this->extractTitle($content);
            $model->content = $content;
            $model->classify = $classify;
            $model->u_id = $uId;

            $model->save();
            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
            $this->setCustomError('添加失败');
            return false;
        }

        return true;
    }

    /**
     * @param $text
     * @return string
     */
    protected function extractTitle($text): string
    {
        // 去除文本两端的空格
        $text = trim($text);

        // 如果文本长度小于 20 字，则直接返回文本
        if (strlen($text) < 20) {
            return $text;
        }

        // 查找第一个空格或标点符号的位置
        $spacePos = strpos($text, ' ');
        $punctuationPos = strpos($text, '。'); // 假设使用中文句号作为标点符号

        // 如果找到了空格或标点符号
        if ($spacePos !== false || $punctuationPos !== false) {
            // 取两者中较小的位置作为截断点
            $cutPos = min($spacePos, $punctuationPos);
            if ($cutPos === false) {
                $cutPos = max($spacePos, $punctuationPos);
            }
            // 提取 20~30 字的标题
            $title = substr($text, 0, $cutPos);
        } else {
            // 如果没有找到空格或标点符号，则截取 20~30 字
            $title = substr($text, 0, 30);
        }

        return $title;
    }

    /**
     * 列表.
     *
     * @param Request $request
     * @return array
     */
    public function noteList(Request $request): array
    {
        $uId = $request->user()->id;
        $name = $request->input('name');
        $page = $request->input('page', 1);
        $size = $request->input('size', 10);
        $classify = $request->input('classify');

        $model = UserNotesModel::getInstance()->where(['u_id' => $uId]);

        if (isset($name)) {
            $model = $model->where('content', 'like', '%' . $name . '%');
        }

        if (isset($classify) && (int)$classify !== 0) {
            $model = $model->where('classify', $classify);
        }

        $res = $model->with('classBy')->orderby('created_at', 'desc')->paginate($size, ['*'], 'page', $page);

        $res->makeHidden(['content']);

        return [
            'list' => $res->items(),
            'total' => $res->total()
        ];
    }

    /**
     * 删除笔记.
     *
     * @param Request $request
     * @return bool
     */
    public function delNotes(Request $request): bool
    {
        $id = $request->input('id');
        $uId = $request->user()->id;

        $noteModel = UserNotesModel::getInstance()->find($id);
        if (!$noteModel) {
            $this->setCustomError('笔记不存在');
            return false;
        }

        if ($noteModel->u_id !== $uId) {
            $this->setCustomError('无权限删除');
            return false;
        }

        try {
            $noteModel->delete();
        } catch (Exception $e) {
            $this->setCustomError('删除失败');
            return false;
        }

        return true;
    }

    /**
     * 获取详情.
     *
     * @param Request $request
     * @return mixed
     */
    public function noteDetail(Request $request): mixed
    {
        $id = $request->input('id');

        return UserNotesModel::getInstance()->find($id);
    }
}
